package com.beiing.tianshuai.tianshuai.network;

import android.content.Context;

import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.app.MyApplication;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 用于Retrofit的初始化
 * Created by magikliu on 2017/7/7.
 */

public class RetrofitHelper {
    private Context context;

    private static RetrofitHelper instance = null;
    private Retrofit retrofit = null;

    public static RetrofitHelper getInstance(Context context) {
        if (instance == null) {
            instance = new RetrofitHelper(context);
        }
        return instance;
    }

    private RetrofitHelper(Context context) {
        this.context = context;
        init();
    }

    private void init() {
        File cacheFile = new File(context.getApplicationContext().getCacheDir(), "cache");
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);

        OkHttpClient client = new OkHttpClient.Builder()
                .cache(cache)
                .retryOnConnectionFailure(false)
                .connectTimeout(60L, TimeUnit.SECONDS)
                .readTimeout(60L, TimeUnit.SECONDS)
                .writeTimeout(60L, TimeUnit.SECONDS)
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(HttpRequestConstant.MAIN_REQUEST_HEAD)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    public RetrofitService getService() {
        return retrofit.create(RetrofitService.class);
    }
}
